package com.lrkj.payfee.controller;

import com.lrkj.common.annotation.Log;
import com.lrkj.common.constant.FeeConstants;
import com.lrkj.common.core.controller.BaseController;
import com.lrkj.common.core.domain.AjaxResult;
import com.lrkj.common.core.page.TableDataInfo;
import com.lrkj.common.enums.BusinessType;
import com.lrkj.common.exception.BaseException;
import com.lrkj.common.utils.StringUtils;
import com.lrkj.common.utils.poi.ExcelUtil;
import com.lrkj.common.utils.uuid.IdUtils;
import com.lrkj.framework.utils.NumberUtils;
import com.lrkj.framework.utils.SerialNumUtil;
import com.lrkj.payfee.domain.*;
import com.lrkj.payfee.service.*;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 生成仪费用Controller
 *
 * @author yajun_ren
 * @date 2021-07-30
 */
@RestController
@RequestMapping("/payfee/generate")
public class GenerateController extends BaseController
{
    @Autowired
    private IGenerateService generateService;

    @Autowired
    private IRuleCostService ruleCostService;

    @Autowired
    private IChargeItemService chargeItemService;

    @Autowired
    private IRoomNormService roomNormService;

    @Autowired
    private ICopyRoomService copyRoomService;



    /**
     * 查询生成仪费用列表
     */
    @ApiOperation(value = "查询生成仪费用列表", notes = "查询生成仪费用列表")
    @GetMapping("/list")
    public TableDataInfo list(Generate generate)
    {
        startPage();
        List<Generate> list = generateService.selectGenerateList(generate);
        return getDataTable(list);
    }

    /**
     * 导出生成仪费用列表
     */
	@ApiOperation(value = "导出生成仪费用列表", notes = "导出生成仪费用列表")
    @PreAuthorize("@ss.hasPermi('payfee:generate:export')")
    @Log(title = "生成仪费用", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(Generate generate)
    {
        List<Generate> list = generateService.selectGenerateList(generate);
        ExcelUtil<Generate> util = new ExcelUtil<Generate>(Generate.class);
        return util.exportExcel(list, "生成仪费用数据");
    }

    /**
     * 获取生成仪费用详细信息
     */
	@ApiOperation(value = "获取生成仪费用详细信息", notes = "获取生成仪费用详细信息")
    @PreAuthorize("@ss.hasPermi('payfee:generate:query')")
    @GetMapping(value = "/{generateId}")
    public AjaxResult getInfo(@PathVariable("generateId") String generateId)
    {
        return AjaxResult.success(generateService.selectGenerateById(generateId));
    }

    /**
     * 新增生成仪费用
     */
	  @ApiOperation(value = "新增生成仪费用", notes = "新增生成仪费用")
    @PreAuthorize("@ss.hasPermi('payfee:generate:add')")
    @Log(title = "生成仪费用", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Generate generate)
    {
        return toAjax(generateService.insertGenerate(generate));
    }

    /**
     * 修改生成仪费用
     */
	 @ApiOperation(value = "修改生成仪费用", notes = "修改生成仪费用")
    @PreAuthorize("@ss.hasPermi('payfee:generate:edit')")
    @Log(title = "生成仪费用", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Generate generate)
    {
        return toAjax(generateService.updateGenerate(generate));
    }

    /**
     * 删除生成仪费用
     */
	 @ApiOperation(value = "删除生成仪费用", notes = "删除生成仪费用")
    @PreAuthorize("@ss.hasPermi('payfee:generate:remove')")
    @Log(title = "生成仪费用", businessType = BusinessType.DELETE)
	@DeleteMapping("/{generateIds}")
    public AjaxResult remove(@PathVariable String[] generateIds)
    {
        return toAjax(generateService.deleteGenerateByIds(generateIds));
    }



    /**
     * 生成费用单
     */
    @Transactional
    @ApiOperation(value = "生成费用单", notes = "生成费用单")
    @PreAuthorize("@ss.hasPermi('payfee:generate:Generate')")
    @Log(title = "生成仪费用", businessType = BusinessType.DELETE)
    @GetMapping("/selGenerIds/{generateIds}")
    public TableDataInfo selGenerIds(@PathVariable String[] generateIds)
    {
       // int rows=0;
        List<RuleCost> list=new ArrayList<>();
        CopyRoom copyRoom=new CopyRoom();
        List<CopyRoom> copyRoomList=new ArrayList<>();
        for (int i = 0; i < generateIds.length; i++) {
            RuleCost ruleCost=new RuleCost();
            //根据所选的id查询出生成仪表费用的数据
            Generate generate= generateService.selectGenerateById(generateIds[i]);
                //已生成的数据
                if (generate.getGenerateState().equals("0")) {

                    if (StringUtils.isNull(generate.getTheReading())){
                        throw new BaseException("请填写本次读数");
                    }else if (StringUtils.isNull(generate.getReadingTime())){
                        throw new BaseException("请填写本次读数日期");
                    }

                    //主键ID
                    ruleCost.setCostId(IdUtils.simpleUUID());
                    //所属房间
                    ruleCost.setRoomId(generate.getRoomId());
                    //所属机构
                    ruleCost.setDeptId(generate.getDeptId());
                    //业主id
                    ruleCost.setOwnerId(generate.getOwnerId());
                    //根据仪表种类id 查询收费项目
                    ChargeItem chargeItem= chargeItemService.selectItemByKindId(generate.getKindId());

                    //单据号
                    ruleCost.setCostNo(this.getNo(FeeConstants.meter_cost_key));
                    //收费项目
                    ruleCost.setChargeId(chargeItem.getChargeId());
                    //收费类型
                    ruleCost.setProjectId(chargeItem.getProjectId());

                    RoomNorm roomNorm= roomNormService.getRoomNormByRoomId(generate.getRoomId(),chargeItem.getChargeId());
                    if (roomNorm==null){
                        throw  new  BaseException("该房间没有绑定收费标准,请在房屋收费标准中绑定");
                    }

                    //根据收费项目id 查询收费标准
                   // ChargeNorm chargeNorm= chargeNormService.selectChargeById(chargeItem.getChargeId());

                    //收费标准
                    ruleCost.setNormId(roomNorm.getNormId());
                    //应收日期
                    ruleCost.setReceivableTime(generate.getLastTime());
                    //计费读数
                    BigDecimal bignum1 = new BigDecimal(String.valueOf(generate.getChargedLine()));
                    //所属仪表种类的单价
                    BigDecimal bignum2 = new BigDecimal(String.valueOf(roomNorm.getAmountSpecified()));
                    //开始时间
                    ruleCost.setBeginTime(generate.getLastTime());
                    //结束时间
                    ruleCost.setFinishTime(generate.getReadingTime());
                    //单价
                    ruleCost.setPrices(roomNorm.getAmountSpecified());
                    //金额
                    ruleCost.setMoneys(bignum1.multiply(bignum2));

                    BigDecimal bigDecima2=new BigDecimal(0.00);


                    //优惠后金额  读数*单价
                    ruleCost.setQueenMoney((bignum1.multiply(bignum2)));

                    //优惠金额
                    ruleCost.setSpecialMoney(bigDecima2);

                    //已收金额
                    ruleCost.setHaveMoney(bigDecima2);
                    //应收金额 读数*单价
                    ruleCost.setReceivableMoney((bignum1.multiply(bignum2)));
                    //祖级ID
                    ruleCost.setAncestors(roomNorm.getAncestors());

                    //欠费金额
                    ruleCost.setAmountOwed((bignum1.multiply(bignum2)));
                    //收费状态
                    ruleCost.setStatus(FeeConstants.charge_status_10001);
                    //rows= ruleCostService.insertRuleCost(ruleCost);
                    list.add(ruleCost);
                    //修改生成仪表单状态
                    generateService.updateState(generateIds[i]);


                    //生成费用单后添加下一条抄表费用
                    //copyRoom.setCopyId(IdUtils.simpleUUID());
                    copyRoom.setRometerId(generate.getRometerId());
                    copyRoom.setOwnerId(generate.getOwnerId());
                    copyRoom.setLastTime(generate.getReadingTime());
                    copyRoom.setLastReading(generate.getTheReading());
                    copyRoom.setRoomId(generate.getRoomId());
                    copyRoomService.insertCopyRoom(copyRoom);
                    //copyRoomList.add(copyRoom);
                }
        }
        ruleCostService.doSaveList(list);
        //copyRoomService.doSaveList(copyRoomList);
        return getDataTable(list);
    }

    private String getNo(String key) {
        int nextVal = SerialNumUtil.getInstance().nextInt(key);
        return key + NumberUtils.frontCompWithZore(nextVal, 7);
    }
}
